package com.item.news.runnable;

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName Top_newsRunnable
 * @Description TODO
 * @Author WangDong
 * @Date 2019/1/21 11:23
 * @Version 1.0
 **/
public class Top_newsRunnable implements Runnable {

    private Jedis jedis;

    public Top_newsRunnable(Jedis jedis) {
        this.jedis = jedis;
    }

    @Override
    public void run() {
        top_news();
    }
    public void top_news() {
        String url = "https://www.163.com/";
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        try {
            Document doc = Jsoup.connect(url).get();
            System.out.println("获取头条信息");
             System.out.println("这是数据：" + doc);

            Elements top_news = doc.select(" div.news_bj_yw>ul.cm_ul_round>li"); //带有href属性的a元素
            for (Element e: top_news){
                HashMap<String,String> maps=new HashMap<String,String>();
                maps.put("title",e.select("a").text());
                String href= e.select("a").attr("href");
                href=href.substring(href.length()-4,href.length());
                if(href.equals("html")){
                    maps.put("href",e.select("a").attr("href"));
                }
                maps.put("tag","");
                maps.put("img","");
                data.add(maps);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(!data.isEmpty()){
            jedis.set("toutiao", JSON.toJSONString(data));
        }
    }
}
